﻿using DAL3;
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.IO.Ports;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace GEMINI_OP10
{
    public partial class FormMain : Form
    {
        public string str = "未连接";
        string strs = "";
        int PLC_Count = 1;
        Socket socketSend;
        public string server = "";
        string[] typeArray = new string[50];
        string[] saoma = new string[2];
        string icID;
        string result;
        public static bool a;   //用于第一次启动给comboBox1赋上型号。
        public string[] alarmNum = new string[20];     //用于读取报警显示
        public bool clear;          //用于清除报警显示
        public bool Photoshow;      //用于展示照片
        public bool Singlerun;          //用于单次判断扫码参数
        public bool Photoshowclear;   //用于拍照合格后，单次清除显示图片。
        //BartenderHelper printlab = new BartenderHelper();
        public struct proData
        {
            public static string typeName;
            public static string Ewm;
            public static string testStation;
            public static string allResult;
            public static double positivePressureValue;
            public static double negativePressureValue;
            public static string operatorter;
            public static string serialNumber;
            public static bool save;
        }
        public struct plcStructIn
        {
            public bool bool_0;
            public bool bool_1;
            public bool bool_2;
            public bool bool_3;
            public bool bool_4;
            public bool bool_5;
            public bool bool_6;
            public bool bool_7;
            public bool bool_8;
            public bool bool_9;
            public bool bool_10;
            public bool bool_11;
            public bool bool_12;
            public bool bool_13;
            public bool bool_14;
            public bool bool_15;

            public Int16 int_0;
            public Int16 int_1;
            public Int16 int_2;
            public Int16 int_3;
            public Int16 int_4;
            public Int16 int_5;
            public Int16 int_6;
            public Int16 int_7;
            public Int16 int_8;
            public Int16 int_9;

        }
        //----线程循环
        bool _Continue = true;
        //----PLC监控线程数组
        Thread[] PLC_Td;
        //PLC实例数组
        public static SimenesPLC[] PLC_Link;
        //PLC DB结构数组
        public plcStructIn[] Struct_Test;
        public static plcStructIn _plcStruct = new plcStructIn();

        public static FormMain FM10;
        public FormMain()
        {
            InitializeComponent();
            FM10 = (FormMain)this;
            //关联打印对象的事件
            printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.LotteryPrintPage);
        }

        private void OpenForm(Form form)
        {
            //将当前子窗体设置成非顶级控件
            form.TopLevel = false;
            //设置窗体最大化
            form.WindowState = FormWindowState.Maximized;
            //设置窗体无边框
            form.FormBorderStyle = FormBorderStyle.None;
            //设置窗体嵌入容器
            form.Parent = this.panel1;
            form.Show();
        }

        private void CloseForm()
        {
            //遍历这个容器里面的所有控件，找出窗体对象
            foreach (Control item in this.panel1.Controls)
            {
                if (item is Form)
                {
                    Form form = (Form)item;
                    form.Close();
                    //移除
                    this.panel1.Controls.Remove(item);
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //嵌入窗口
            //this.CloseForm();
            FormUserLoginInterface formUserLoginInterface = new FormUserLoginInterface();
            //this.OpenForm(formUserLoginInterface);
            formUserLoginInterface.Show();
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭主窗体时释放后台线程的资源
            for (int I = 0; I < PLC_Count; I++)
            {
                if (PLC_Td[I] != null)
                {
                    PLC_Td[I].Abort();
                }
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            //取消跨线程的访问
            Control.CheckForIllegalCrossThreadCalls = false;
            #region 连接PLC
            PLC_Td = new Thread[PLC_Count];
            PLC_Link = new SimenesPLC[PLC_Count];
            Struct_Test = new plcStructIn[PLC_Count];
            for (int I = 0; I < PLC_Count; I++)
            {
                PLC_Td[I] = new Thread(PLC_Td_Func);
                PLC_Td[I].IsBackground = true;
                PLC_Td[I].Start(I);
            }
            #endregion

            #region 与服务器tcp/ip通讯建立连接
            //try
            //{
            //    //创建负责通信的Socket
            //    socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //    IPAddress ip = IPAddress.Parse("192.168.1.150");
            //    IPEndPoint point = new IPEndPoint(ip, 50001);
            //    //获得要连接的远程服务器应用程序的IP地址和端口号
            //    socketSend.Connect(point);
            //    server = "成功";

            //    //开启一个新的线程不停的接收服务端发来的消息
            //    Thread th = new Thread(Recive);
            //    th.IsBackground = true;
            //    th.Start();
            //}
            //catch
            //{
            //    server = "失败";
            //}
            #endregion

            #region 向服务器获取所有产品型号和扫码设置
            //string sql = "select [typeName],[OP10扫码] from parameterSetting";
            //SqlDataReader objReader = SQLHelp.GetReader(sql);
            //int temp2 = 0;
            //while (objReader.Read())
            //{
            //    //comboBox1.Items.Add(objReader["OP10扫码"].ToString());
            //    typeArray[temp2] = objReader["typeName"].ToString();
            //    temp2 += 1;
            //}
            //objReader.Close();
            var fils = Directory.GetFiles(Application.StartupPath + "\\" + "型号", "*.txt");
            for (int i = 0; i < fils.Length; i++)
            {
                comboBox1.Items.Add(fils[i].Substring(fils[i].LastIndexOf("\\") + 1, fils[i].Length - 4 - (fils[i].LastIndexOf("\\") + 1)));
            }
            #endregion

            #region 设置串口参数并打开串口接收
            //波特率

            //IC卡
            //serialPort1.BaudRate = 9600;
            //扫码
            serialPort2.BaudRate = 115200;

            //数据位

            //IC卡
            //serialPort1.DataBits = 8;
            //扫码
            serialPort2.DataBits = 8;

            //奇偶校验位
            //serialPort1.Parity = System.IO.Ports.Parity.None;
            serialPort2.Parity = System.IO.Ports.Parity.None;

            //停止位
            //serialPort1.StopBits = System.IO.Ports.StopBits.One;
            serialPort2.StopBits = System.IO.Ports.StopBits.One;
            string[] contents = new string[5];
            try
            {
                contents = File.ReadAllLines(Application.StartupPath + "\\COM口配置.txt", Encoding.UTF8);
            }
            catch
            {
                label28.Text += "请检查COM口配置！";
            }
            //端口
            //try
            //{
            //serialPort1.PortName = contents[0];
            // serialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
            //serialPort1.Open();

            //}
            //catch
            //{
            //MessageBox.Show("IC卡COM1端口打开失败，请检查串口连接是否正确！", "错误提示");
            //}

            try
            {
                serialPort2.PortName = contents[1];
                serialPort2.DataReceived += new SerialDataReceivedEventHandler(SerialPort2_DataReceived);
                serialPort2.Open();
            }
            catch
            {
                MessageBox.Show("扫码端口打开失败，请检查串口连接是否正确！", "错误提示");
            }
            #endregion
        }
        //PLC线程
        bool printDone;
        private string[] stepNum = new string[20];      //建立stepNum用于接受步骤
        private void PLC_Td_Func(object ob)
        {
            Ping p = new Ping();
            int num = (int)ob;

            string[] PLC_IP = new string[PLC_Count];
            PLC_IP[0] = "172.16.13.10";
            PLC_Link[num] = new SimenesPLC(CpuType.S71200, PLC_IP[num].ToString(), 0, 1);
            while (_Continue)
            {
                try
                {
                    //处理相应的PLC对象的数据处理
                    if (p.Send(PLC_IP[num], 200).Status == IPStatus.Success)//如果200ms时间间隔ping通了
                    {
                        if (PLC_Link[num].plc.IsConnected == false)//plc没有连接上
                        {
                            try
                            {
                                PLC_Link[0].plc.Open();
                                SimenesPLC.conectStatus = true;
                                str = "成功";
                            }
                            catch (Exception)
                            {
                                SimenesPLC.conectStatus = false;
                                str = "失败";
                                //throw;
                            }
                        }
                        else
                        {
                            str = "成功";
                            //读取DB
                            //Struct_Test[num] = (plcStructIn)PLC_Link[num].plc.ReadStruct(typeof(plcStructIn), 63, 0);
                            //_plcStruct = Struct_Test[num];
                            //Int16 type = (Int16)PLC_Link[num].plc.Read(DataType.DataBlock, 63, 26, VarType.Int, 1, 0);
                            //try
                            //{
                            //    string sql1 = "select [产品系列号] from parameterSetting where typeName = '{0}'";
                            //    sql = string.Format(sql1, label2.Text);
                            //    SqlDataReader objReader1 = SQLHelp.GetReader(sql);
                            //    while (objReader1.Read())
                            //    {
                            //        typeNameTemp = Convert.ToInt32(objReader1["产品系列号"]) + 1;

                            //    }
                            //    objReader1.Close();

                                //pictureBox3.Image = Image.FromFile(Application.StartupPath + @"\SOP\" + 3 + ".png");
                            //}
                            //catch (Exception)
                            //{
                            //    //throw;
                            //}
                            //if (a)
                            //{
                            //    int i = comboBox1.SelectedIndex + 1;
                            //    pictureBox3.Image = Image.FromFile(Application.StartupPath + @"\SOP\" + i + ".png");
                            //}
                            //else
                            //{

                            //}
                            if (pictureBox3.BackgroundImage is null)
                            {
                                Photoshow = false;
                                int i = comboBox1.SelectedIndex + 1;
                                pictureBox3.BackgroundImage = Image.FromFile(Application.StartupPath + @"\SOP\" + i + ".png");
                            }
                            else
                            {
                                //pictureBox3.Image = null;
                            }
                            #region  报警记录
                            //报警记录


                            #endregion

                            if (!a)     //避免每次启动都要手动选型
                            {
                                int c;
                                c = Convert.ToInt32(PLC_Link[0].ReadByte(DataType.DataBlock, 99, 27)) - 1; //读取PLC中的型号
                                comboBox1.SelectedIndex = c;   //首次启动自动选择PLC现在保持着的型号。
                                int i = comboBox1.SelectedIndex + 1;
                                pictureBox3.BackgroundImage = Image.FromFile(Application.StartupPath + @"\SOP\" + i + ".png");
                                a = true;
                            }
                            else
                            {

                            }
                            if (comboBox1.Text != "")
                            {
                                if (readSeting[0].Equals("0"))      //增加第一行零件码用于数据存储。
                                {
                                    label20.Visible = false;
                                    label21.Visible = false;
                                }
                                else
                                {
                                    label20.Visible = true;
                                    label21.Visible = true;
                                    label21.Text = readSeting[0];
                                }
                                if (readSeting[2].Equals("0"))
                                {
                                    label23.Visible = false;
                                    label22.Visible = false;
                                }
                                else
                                {
                                    label23.Visible = true;
                                    label22.Visible = true;
                                    label23.Text = readSeting[0];
                                }

                                if (readSeting[4].Equals("0"))
                                {
                                    label25.Visible = false;
                                    label24.Visible = false;
                                }
                                else
                                {
                                    label25.Visible = true;
                                    label24.Visible = true;
                                    label25.Text = readSeting[2];
                                }
                                if (true/*readSeting[4].Equals("0")*/)  //隐藏第三个零件码
                                {
                                    label17.Visible = false;
                                    label27.Visible = false;
                                }
                                else
                                {
                                    label17.Visible = true;
                                    label27.Visible = true;
                                    label17.Text = readSeting[4];
                                }
                                //螺钉1
                                if (readSeting[6].Equals("0"))
                                {
                                    label41.Visible = false;
                                    label42.Visible = false;
                                    label43.Visible = false;
                                    label46.Visible = false;
                                    label47.Visible = false;
                                }
                                else
                                {
                                    label41.Visible = true;
                                    label42.Visible = true;
                                    label43.Visible = true;
                                    label46.Visible = true;
                                    label47.Visible = true;
                                    label46.Text = readSeting[6];
                                    PLC_Link[0].WriteByte("DB99.DBB1", Convert.ToByte(label46.Text));
                                }
                                //螺钉2
                                if (readSeting[7].Equals("0"))
                                {
                                    label44.Visible = false;
                                    label48.Visible = false;
                                    label49.Visible = false;
                                }
                                else
                                {
                                    label44.Visible = true;
                                    label48.Visible = true;
                                    label49.Visible = true;
                                    label48.Text = readSeting[7];
                                    PLC_Link[0].WriteByte("DB99.DBB2", Convert.ToByte(label48.Text));
                                }
                                //if (comboBox1.Text.Contains("百度"))
                                //{
                                //    label1.Visible = false;
                                //    label2.Visible = false;
                                //    label20.Visible = false;
                                //    label21.Visible = false;
                                //}
                                //else
                                //{
                                //    label1.Visible = false;
                                //    label2.Visible = false;
                                //    label20.Visible = false;
                                //    label21.Visible = false;
                                //}
                                if (!Singlerun)    //单次判断扫码参数全为0时直接给PLC扫码完成信号。
                                {
                                    if (readSeting[1].Equals("0") && readSeting[3].Equals("0") && readSeting[5].Equals("0"))
                                    {
                                        PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 10, 0, 1);
                                        //PLC_Link[0].WriteBoolen("DB99.DBX10.0", true);
                                        Singlerun = true;
                                    }
                                }
                            }


                            //测试时间
                            label7.Text = (PLC_Link[0].readInt("DB99.DBW42") / 60).ToString() + "分" + (PLC_Link[0].readInt("DB99.DBW42") / 60).ToString() + "秒";
                            //计划生产数
                            label9.Text = PLC_Link[0].readInt("DB99.DBW32").ToString();
                            //当前生产数
                            label11.Text = PLC_Link[0].readInt("DB99.DBW34").ToString();
                            //合格数
                            label13.Text = PLC_Link[0].readInt("DB99.DBW36").ToString();
                            //不合格数
                            label15.Text = PLC_Link[0].readInt("DB99.DBW38").ToString();
                            //自动模式状态
                            if (PLC_Link[0].readBoolen("DB1050.DBX22.0"))
                            {
                                button9.BackColor = Color.Green;
                            }
                            else
                            {
                                button9.BackColor = Color.Silver;
                            }
                            //手动模式状态
                            if (PLC_Link[0].readBoolen("DB1050.DBX22.1"))
                            {
                                button5.BackColor = Color.Green;
                            }
                            else
                            {
                                button5.BackColor = Color.Silver;
                            }
                            //报警复位
                            if (FormMain.PLC_Link[0].readBoolen("DB1050.DBX1.2"))
                            {
                                button10.BackColor = Color.Green;   
                            }
                            else
                            {
                                button10.BackColor = Color.Silver;
                            }
                            //打钉
                            try
                            {
                                //螺钉1设置数
                                label46.Text = PLC_Link[0].ReadByte(DataType.DataBlock, 99, 1).ToString();
                                //螺钉1完成数
                                label47.Text = PLC_Link[0].ReadByte(DataType.DataBlock, 99, 25).ToString();
                                //螺钉2设置数
                                label48.Text = PLC_Link[0].ReadByte(DataType.DataBlock, 99, 2).ToString();
                                //螺钉2完成数
                                label49.Text = PLC_Link[0].ReadByte(DataType.DataBlock, 99, 26).ToString();
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                            //步骤提示
                            try
                            {
                                stepNum = File.ReadAllLines(Application.StartupPath + "\\步骤配置.txt", Encoding.UTF8);
                                label51.Text = stepNum[PLC_Link[0].readInt("DB1050.DBW84.0")];
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                            //label28.Text = label28Temp;
                            if (PLC_Link[0].readBoolen("DB1050.DBX22.4"))    //DB1050.DBX22.4照片显示
                            {
                                //timerPhoto.Stop();
                                Thread.Sleep(1000);
                                Photoshow = true;
                                //timerPhoto.Enabled = true;
                                //timerPhoto.Interval = 1000;
                                //timerPhoto.AutoReset = false;
                                //timerPhoto.Elapsed += new System.Timers.ElapsedEventHandler(timerPhoto_Elapsed);

                                //timerPhoto.Start();
                                string filePath = GetLatestPhoto();
                                if (!string.IsNullOrEmpty(filePath))
                                {
                                    if (pictureBox3.Image != null)
                                    {
                                        pictureBox3.Image.Dispose();
                                    }

                                    if ((pictureBox3.Tag !=null&& !pictureBox3.Tag.ToString().Equals(filePath))||pictureBox3.Tag==null)
                                    {
                                        // 显示最新照片
                                        pictureBox3.BackgroundImage = Image.FromFile(filePath);
                                        pictureBox3.Tag = filePath;
                                    }


                                    //if (pictureBox3.Tag == null)
                                    //{
                                    //    // 显示最新照片
                                    //    pictureBox3.BackgroundImage = Image.FromFile(filePath);
                                    //    pictureBox3.Tag = filePath;
                                    //}
                                    //else
                                    //{
                                    //    if (!pictureBox3.Tag.ToString().Equals(filePath))
                                    //    {
                                    //        // 显示最新照片
                                    //        pictureBox3.BackgroundImage = Image.FromFile(filePath);
                                    //        pictureBox3.Tag = filePath;
                                    //    }
                                    //}

                                    //else if (!pictureBox3.Tag.ToString().Equals(filePath))
                                    //{
                                    //    // 显示最新照片
                                    //    pictureBox3.BackgroundImage = Image.FromFile(filePath);
                                    //    pictureBox3.Tag = filePath;
                                    //}


                                    if (!Photoshowclear)
                                    {
                                        Photoshowclear = true;
                                    }
                                    //PLC_Link[0].WriteBoolen("DB1050.DBX22.4", false);   //显示完图片后清除PLC信号。
                                }
                            }
                            else if (Photoshowclear && !PLC_Link[0].readBoolen("DB1050.DBX22.4"))
                            {
                                //Photoshow = false;
                                if (pictureBox3.Image != null)
                                {
                                    pictureBox3.Image.Dispose();
                                }
                                pictureBox3.Image = null;
                                Photoshowclear = false;
                                //MoveAndRenameLatestPhoto("D:\\保存照片\\" + DateTime.Now.ToString("yyyyMMdd"), label20.Text);
                                //pictureBox3.Image = Image.FromFile("SOP\\公司新logo.jpg");
                            }
                            else
                            {

                            }
                            if (PLC_Link[0].readBoolen("DB99.DBX24.4"))
                            {
                                //label28.Text = "读取到过程完成信号";
                                proData.save = true;
                            }
                            else
                            {
                                proData.save = false;
                            }
                            if (PLC_Link[0].readBoolen("DB99.DBX24.5"))
                            {
                                result = "合格";
                                label26.Text = "合格";
                                label26.BackColor = System.Drawing.Color.Green;

                            }
                            else if (PLC_Link[0].readBoolen("DB99.DBX24.6"))
                            {
                                result = "不合格";
                                label26.Text = "不合格";
                                label26.BackColor = System.Drawing.Color.Red;
                            }
                            else
                            {
                                result = "未完成";
                                label26.Text = "未完成";
                                label26.BackColor = System.Drawing.Color.Silver;
                                if (saveData  || PLC_Link[0].readBoolen("DB1050.DBX1.1") || PLC_Link[0].readBoolen("DB1050.DBX1.5"))        //数据记录完成或者读到返回原位（大复位）信号，进行清0初始化操作
                                {
                                    //label28.Text = "开始初始化";
                                    if (saveData == true)
                                    {
                                        if (pictureBox3.Image != null)
                                        {
                                            pictureBox3.Image.Dispose();
                                        }
                                        MoveAndRenameLatestPhoto("D:\\保存照片\\" + DateTime.Now.ToString("yyyyMMdd"), label20.Text.Substring(23, 10));     //后续图片与蒸发器码绑定
                                        //pictureBox3.Image.Dispose();
                                        pictureBox3.Image = null;
                                        //pictureBox3.Image = Image.FromFile("SOP\\公司新logo.jpg");
                                    }
                                    label20.Text = "";
                                    label20.BackColor = System.Drawing.Color.Silver;
                                    label22.Text = "";
                                    label22.BackColor = System.Drawing.Color.Silver;
                                    label24.Text = "";
                                    label24.BackColor = System.Drawing.Color.Silver;
                                    label27.Text = "";
                                    label27.BackColor = System.Drawing.Color.Silver;
                                    //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 63, 22, 1, 0);
                                    //if (_plcStruct.bool_2 == false)
                                    //{
                                    //    Bitmap bm = new Bitmap(pictureBox3.Width, pictureBox3.Height);
                                    //    pictureBox3.DrawToBitmap(bm, pictureBox3.ClientRectangle);
                                    //    bm.Save(@"D:\照片\" + printTemp + ".bmp");
                                    //    bm.Dispose();
                                    //    deletePhtor(@"d:\1", ".jpeg");
                                    //}
                                    tempEM1ok = false;
                                    tempEM2ok = false;
                                    tempEM3ok = false;
                                    tempEM4ok = false;
                                    //b = false;
                                    //if (saveData == true)
                                    //{
                                    //    if (pictureBox3.Image != null)
                                    //    {
                                    //        pictureBox3.Image.Dispose();
                                    //    }
                                    //    MoveAndRenameLatestPhoto("D:\\保存照片\\" + DateTime.Now.ToString("yyyyMMdd"), label20.Text);     //后续图片与蒸发器码绑定
                                    ////    pictureBox3.Image = Image.FromFile("SOP\\公司新logo.jpg");
                                    //}
                                    printDone = false;
                                    saveData = false;
                                    proData.save = false;
                                    Photoshow = false;
                                    //timerPhoto.Stop();
                                    //pictureBox3.Image = null;
                                }

                                //if (PLC_Link[0].readBoolen("DB99.DBX24.3") && printDone == false)
                                //{
                                ////printDoc.DefaultPageSettings.PrinterSettings.PrinterName = "Argox CP-3140L PPLB";
                                //    //this.printDoc.Print();

                                //    PrintMethod2(@"D:\过程条码OK.btw", "Argox CP-3140L PPLB");
                                //    printDone = true;
                                //}

                                //if (_plcStruct.bool_0)
                                //{
                                //    result = "合格";
                                //    label26.Text = "合格";
                                //    label26.BackColor = Color.Green;
                                //    this.printDoc.Print();
                                //    proData.save = true;
                                //}
                                //else if (_plcStruct.bool_1)
                                //{
                                //    result = "不合格";
                                //    label26.Text = "不合格";
                                //    label26.BackColor = Color.Red;
                                //}
                                //else
                                //{
                                //    result = "未测试";
                                //    label26.Text = "未测试";
                                //    label26.BackColor = Color.Silver;
                                //    if (saveData)
                                //    {
                                //        label20.Text = "";
                                //        label20.BackColor = System.Drawing.Color.Silver;
                                //        label22.Text = "";
                                //        label22.BackColor = System.Drawing.Color.Silver;
                                //        label24.Text = "";
                                //        label24.BackColor = System.Drawing.Color.Silver;
                                //        PLC_Link[0].plc.WriteBit(DataType.DataBlock, 63, 22, 1, 0);
                                //        if (_plcStruct.bool_2 == false)
                                //        {
                                //            Bitmap bm = new Bitmap(pictureBox3.Width, pictureBox3.Height);
                                //            pictureBox3.DrawToBitmap(bm, pictureBox3.ClientRectangle);
                                //            bm.Save(@"D:\照片\" + printTemp + ".bmp");
                                //            bm.Dispose();
                                //            deletePhtor(@"d:\1", ".jpeg");
                                //        }
                                //        tempEM1ok = false;
                                //        tempEM2ok = false;
                                //        tempEM3ok = false;
                                //        printDone = false;

                                //        saveData = false;
                                //    }
                                //    proData.save = false;
                                //}

                            }
                            //数据记录
                            proData.operatorter = Program.userlogin.Admin;//操作员
                            if (!saveData && proData.save)      //无数据记录，直接给数据记录完成
                            {
                                //int data1ok = 0;
                                //int data2ok = 0;
                                //#region 记录到access
                                //string sql = "insert into productData([结束时间],[结果],[内部码],[节拍],[枪1螺钉数],[枪2螺钉数],[扫码1名称],[扫码2名称],[扫码1内容],[扫码2内容]) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')";
                                //sql = string.Format(sql, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), label26.Text, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")/*label20.Text*/, label7.Text, label47.Text, label49.Text, label23.Text, label25.Text, label22.Text, label24.Text);
                                //try
                                //{
                                //    if (data1ok == 0)
                                //    {
                                //        data1ok = SQLHelpaccess.AddData(sql);
                                //    }
                                //}
                                //catch (Exception)
                                //{
                                //    throw;
                                //}
                                //if (data1ok == 1)
                                //{
                                //label28.Text = "给数据记录完成信号";
                                saveData = true;
                                PLC_Link[0].WriteBoolen("DB99.DBX10.2", true);
                                //}
                                //#endregion
                                //#region 记录到sql server
                                //string sql = "insert into productData([OP10-1完成时间],[ID],[内部码],[OP10-1节拍],[OP10-1枪1螺钉数],[OP10-1枪2螺钉数]) values('{0}','{1}','{2}','{3}','{4}','{5}')";
                                //sql = string.Format(sql, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"), PLC_Link[0].readDInt("DB13.DBD0"), label20.Text, label7.Text, label47.Text, label49.Text);
                                //try
                                //{

                                //    if (data1ok == 0)
                                //    {
                                //        data1ok = SQLHelp.AddData(sql);
                                //    }

                                //}
                                //catch (Exception e)
                                //{
                                //    throw;
                                //}
                                //string sql1 = "insert into tiaoma([内部码],[ID],[OP10-1扫码1],[OP10-1扫码2],[OP10-1扫码1名称],[OP10-1扫码2名称]) values('{0}','{1}','{2}','{3}','{4}','{5}')";
                                //sql1 = string.Format(sql1, label20.Text, PLC_Link[0].readDInt("DB13.DBD0"), label22.Text, label24.Text, label23.Text, label25.Text);
                                //try
                                //{
                                //    if (data2ok == 0)
                                //    {
                                //        data2ok = SQLHelp.AddData(sql1);
                                //    }
                                //}
                                //catch (Exception e)
                                //{
                                //    throw;
                                //}
                                //if (data1ok == 1 && data2ok == 1)
                                //{
                                //    saveData = true;
                                //    PLC_Link[0].WriteBoolen("DB99.DBX10.2", true);
                                //}
                                //else
                                //{
                                //    MessageBox.Show("数据记录失败");
                                //} 
                                //#endregion
                            }
                        }
                    }
                    else
                    {
                        //PLC_Link[num].plc.Close();
                        str = "ping失败";
                    }
                }
                catch (Exception ex1)
                {
                    
                    //MessageBox.Show(Convert.ToString(ex1), "错误提示!");
                }
                if (str.Equals("成功"))
                {
                    label5.BackColor = System.Drawing.Color.Green;
                }
                else
                {
                    label5.BackColor = System.Drawing.Color.Red;
                }
                Thread.Sleep(100);
                //label242.Text = string.Format("使用公司：空调国际(上海)有限公司   \t 设备公司：重庆英之拓智能设备有限公司  \t  软件版本号：V2.0", Program.userlogin.name);
                if (label242.Text == "")
                {
                    label242.Text = string.Format("使用公司：空调国际(上海)有限公司   \t 设备公司：重庆英之拓智能设备有限公司  \t  软件版本号：V2.0", Program.userlogin.name);

                }
                else
                {

                }
            }

        }

        /// <summary>
        /// 不停的接受服务器发来的消息
        /// </summary>
        void Recive()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024];
                    int r = socketSend.Receive(buffer);
                    //实际接收到的有效字节数
                    if (r == 0)
                    {
                        break;
                    }
                    //表示发送的字符消息,并且是所有产品型号
                    if (buffer[0] == 0)
                    {
                        string s = Encoding.UTF8.GetString(buffer, 1, r - 1);

                        //0 5 ,aaa,asas,dsds,gfhh,hhggh,
                        //截取所有型号
                        typeArray = s.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    }
                    //表示发送的字符消息,并且是扫码参数
                    if (buffer[0] == 1)
                    {
                        string s = Encoding.UTF8.GetString(buffer, 1, r - 1);
                        //1,hhggh
                        //截取扫码参数设置
                        saoma = s.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    }


                }
                catch { }

            }
        }

        //IC卡

        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //try
            //{

            //    Thread.Sleep(50);
            //    byte[] byteRead1 = new byte[serialPort1.BytesToRead];
            //    serialPort1.Read(byteRead1, 0, byteRead1.Length);
            //    byte[] temp6 = new byte[1];
            //    temp6[0] = byteRead1[20];
            //    icID = byteToHexStr(temp6, 1);
            //    Program.userlogin = UserManagement.GetUser(Convert.ToInt32(icID));
            //    label242.Text = "当前登录用户：{0} \t\t  使用公司：空调国际  \t 设备公司：重庆英之拓  \t PLC连接{1} \t 连接服务器{2} \t  软件版本号：V1.0";
            //    label242.Text = string.Format(label242.Text, Program.userlogin.name, str, server);
            //}
            //catch (Exception exc)
            //{
            //    MessageBox.Show(exc + "接收失败");
            //}

        }
        //扫码枪
        bool tempEM1ok;
        bool tempEM2ok;
        bool tempEM3ok;
        bool tempEM4ok;
        //bool b;     //左边扫两次码后给一次扫码OK；
        private void SerialPort2_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                Thread.Sleep(100);
                byte[] byteRead = new byte[serialPort2.BytesToRead];
                serialPort2.Read(byteRead, 0, byteRead.Length);
                string indata = Encoding.UTF8.GetString(byteRead);
                label1.Text = indata;

                //if (indata.Contains("DIDI"))      
                //{
                //    label20.Text = indata;
                //    label20.BackColor = Color.Green;
                //    tempEM1ok = true;
                //}
                if (!readSeting[1].Equals("0") && tempEM1ok == false)
                {

                    if (indata.Contains(readSeting[1]))
                    {
                        label20.Text = indata;
                        label20.BackColor = Color.Green;
                        tempEM1ok = true;
                    }

                }
                else
                {
                    tempEM2ok = true;
                }

                if (!readSeting[3].Equals("0") && tempEM2ok == false)
                {

                    if (indata.Contains(readSeting[3]))
                    {
                        label22.Text = indata;
                        label22.BackColor = Color.Green;
                        tempEM2ok = true;
                    }

                }
                else
                {
                    tempEM2ok = true;
                }

                if (!readSeting[5].Equals("0") && tempEM3ok == false)
                {

                    if (indata.Contains(readSeting[5]) && (label22.Text != indata))
                    {
                        label24.Text = indata;
                        label24.BackColor = Color.Green;
                        tempEM3ok = true;
                    }
                }
                else
                {
                    tempEM3ok = true;
                }
                ////判断左边三次扫码完成
                //if (tempEM1ok && tempEM2ok && tempEM3ok /*&& b == false*/)
                //{
                //    PLC_Link[0].WriteBoolen("DB99.DBX10.0", true);
                //    //b = true;
                //}
                //if (!readSeting[5].Equals("0") && tempEM4ok == false)
                //{

                //    if (indata.Contains(readSeting[5]) && (label24.Text != indata))
                //    {
                //        label27.Text = indata;
                //        label27.BackColor = Color.Green;
                //        tempEM4ok = true;
                //    }
                //}
                //else
                //{
                //    tempEM4ok = true;
                //}

                //判定是否所有扫码都ok
                if (tempEM1ok && tempEM2ok && tempEM3ok /*&& tempEM4ok*/)
                {
                    PLC_Link[0].WriteBoolen("DB99.DBX10.0", true);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc + "接收失败");
            }

        }
        public string byteToHexStr(byte[] bytes, int len)  //数组转十六进制字符
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < len; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
        private static byte[] strToToHexByte(string hexString) //字符串转16进制
        {
            //hexString = hexString.Replace(" ", " "); 
            if ((hexString.Length % 2) != 0)
                hexString = "0" + hexString;
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        
        #region 标签打印
        PrintDocument printDoc = new PrintDocument();//创建打印对象

        private void button7_Click(object sender, EventArgs e)
        {
            //printDoc.DefaultPageSettings.PrinterSettings.PrinterName = "Argox CP-3140L PPLB";
            //this.printDoc.Print();
            PrintMethod2(@"D:\过程条码OK.btw", "Argox CP-3140L PPLB");
        }

        private void LotteryPrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            this.PrintLottery(e);
        }
        string printTemp;
        public void PrintLottery(System.Drawing.Printing.PrintPageEventArgs e)
        {
            if (4 - yesterday.Substring(7).Length > 0)
            {
                string sn = "";
                for (int i = 0; i < 4 - yesterday.Substring(7).Length; i++)
                {
                    sn += 0;
                }
                tempNum = sn + Convert.ToInt32(yesterday.Substring(7));
            }
            else
            {
                tempNum = yesterday.Substring(7);
            }
            Font font = new Font("黑体", 9, (FontStyle)Enum.Parse(typeof(FontStyle), "Bold"));//内容字体
            //Font font = new Font("黑体", 9);
            printTemp = "DIDI" + DateTime.Now.ToString("yyyyMMdd") + tempNum;
            e.Graphics.DrawImage(getnew(getqrcode(printTemp, 3), 1), new Point(20, 5));

            e.Graphics.DrawString(printTemp, font, Brushes.Blue, 5, 80, new StringFormat());

        }

        public Bitmap getnew(Bitmap bit, double beishu)//beishu参数为放大的倍数。放大缩小都可以，0.8即为缩小至原来的0.8倍
        {
            Bitmap destBitmap = new Bitmap(Convert.ToInt32(bit.Width * beishu), Convert.ToInt32(bit.Height * beishu));
            Graphics g = Graphics.FromImage(destBitmap);
            g.Clear(Color.Transparent);
            //设置画布的描绘质量           
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.DrawImage(bit, new Rectangle(0, 0, destBitmap.Width, destBitmap.Height), 0, 0, bit.Width, bit.Height, GraphicsUnit.Pixel);
            g.Dispose();
            return destBitmap;
        }

        public Bitmap getqrcode(string content, int height)
        {
            var encoder = new QrEncoder(ErrorCorrectionLevel.M);

            QrCode qrCode = encoder.Encode(content);

            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(height, QuietZoneModules.Two), Brushes.Black, Brushes.White);//如需改变二维码大小，调整12即可
            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);

            Bitmap map = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics g = Graphics.FromImage(map);
            render.Draw(g, qrCode.Matrix);
            return map;
        }

        public void PrintMethod2(string pathLabel, string printName)
        {

            if (4 - yesterday.Substring(7).Length > 0)
            {
                string sn = "";
                for (int i = 0; i < 4 - yesterday.Substring(7).Length; i++)
                {
                    sn += 0;
                }
                tempNum = sn + Convert.ToInt32(yesterday.Substring(7));
            }
            else
            {
                tempNum = yesterday.Substring(7);
            }

            BTprintData.Add("型号", "DIDI-MONA");
            BTprintData.Add("日期", DateTime.Now.ToString("yyMMdd"));
            BTprintData.Add("序列号", tempNum);
            BTprintData.Add("二维码", "DIDI-MONA/AINT/" + DateTime.Now.ToString("yyMMdd") + tempNum + "/accessory line");

            //printlab.BTPrint(pathLabel, BTprintData, out label28Temp, 1, printName);

            BTprintData.Clear();

            strfile = JsonConvert.SerializeObject(System.DateTime.Now.ToString("yyMMdd") + "," + (Convert.ToInt32(yesterday.Substring(7)) + 1).ToString());
            File.WriteAllText("d:\\yesterday.txt", strfile);
        }
        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            label18.Text = DateTime.Now.ToString("yyyy/MM/dd");
            label19.Text = DateTime.Now.ToLongTimeString();
            ////显示拍照照片 D:\1 d:\1\AS_QQbrowser@2x.jpg
            //string file = GetLatestFileNameInfo(@"d:\\1", ".jpeg");
            //if (file != null)
            //{
            //    try
            //    {
            //        pictureBox3.Image = Image.FromFile(file);
            //        //pictureBox3.Image.Dispose();
            //    }
            //    catch
            //    {

            //    }
            //}
            //else
            //{

            //}
            GC.Collect();

            yesterday = File.ReadAllText(@"D:\yesterday.txt");
            yesterday = JsonConvert.DeserializeObject<string>(yesterday);
            if (yesterday.Substring(0, 6) != System.DateTime.Now.ToString("yyMMdd"))
            {
                //PLC_Link[0].plc.Write(DataType.DataBlock, 101, 0, 1);
                strfile = JsonConvert.SerializeObject(System.DateTime.Now.ToString("yyMMdd") + ",1");
                File.WriteAllText("d:\\yesterday.txt", strfile);
            }
            else
            {

            }
            //报警
            try
            {
                if (PLC_Link[0].ReadByte(DataType.DataBlock, 1080, 2) > 0)
                {
                    alarmNum = File.ReadAllLines(System.Windows.Forms.Application.StartupPath + "\\报警配置.txt", Encoding.UTF8);
                    for (int i = 0; i < 8; i++)
                    {
                        if (PLC_Link[0].readBoolen("DB1080.DBX2." + i.ToString()))
                        {
                            //inAlarm("OA报警[1]夹紧气缸前进超时A"); 
                            label242.Text = alarmNum[i];
                            clear = true;
                            break;
                        }
                    }
                }
                //else if (PLC_Link[0].ReadByte(DataType.DataBlock, 10080, 3) > 0)
                //{
                //    alarmNum = File.ReadAllLines(Application.StartupPath + "\\报警配置.txt", Encoding.UTF8);
                //    for (int i = 0; i < 8; i++)
                //    {
                //        if (PLC_Link[0].readBoolen("DB10080.DBX3." + i.ToString()))
                //        {
                //            //inAlarm("OA报警[1]夹紧气缸前进超时A"); 
                //            label242.Text = alarmNum[i + 8];
                //            break;
                //        }
                //    }
                //}
                else
                {
                    if (clear)
                    {
                        label242.Text = "";
                        clear = false;
                    }
                }
                if (Photoshow)
                {
                    button11.BackColor = Color.Green;   //查看拍照
                }
                else
                {
                    button11.BackColor = Color.Silver;
                }
            }
            catch
            {

            }
        }
        //获取最新照片
        static string GetLatestFileNameInfo(string dir, string ext)
        {
            DirectoryInfo d = new DirectoryInfo(dir);
            DateTime temp = new DateTime();
            string FileName = "0";
            //Directory.GetFiles(Application.StartupPath + "\\" + "型号", "*.txt");
            foreach (FileInfo file in d.GetFiles())
            {
                if (file.Extension.ToUpper() == ext.ToUpper())
                {
                    if (file.CreationTime > temp)
                    {
                        temp = file.CreationTime;
                        FileName = file.FullName;
                    }
                }
            }

            return FileName;
        }
        //删除照片
        static string deletePhtor(string dir, string ext)
        {
            DirectoryInfo d = new DirectoryInfo(dir);
            string FileName = "0";

            foreach (FileInfo file in d.GetFiles())
            {
                if (file.Extension.ToUpper() == ext.ToUpper())
                {
                    try
                    {
                        File.Delete(file.FullName);
                    }
                    catch
                    { }
                }
            }

            return FileName;
        }
        private void button8_Click(object sender, EventArgs e)
        {
            if ((Program.userlogin.UserID == 1) || (Program.userlogin.UserID == 2))      //登录账户有操作权限
            {
                FormSeting formSeting = new FormSeting();
                formSeting.Show();
            }
            else    //进行登录操作
            {
                MessageBox.Show("没有操作权限", "提示！");
                return;
            }
        }
        string[] readSeting = new string[5];
        private bool saveData;
        public static Dictionary<string, string> BTprintData = new Dictionary<string, string>();
        private string label28Temp;
        private string yesterday;
        private string strfile;
        private string tempNum;

        ////查看拍照
        //System.Timers.Timer timerPhoto = new System.Timers.Timer();

        //void timerPhoto_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        //{
        //    //显示拍照照片
        //    string file = GetLatestFileNameInfo(@"d:\\photo", ".jpeg");
        //    if (file != null)
        //    {
        //        try
        //        {
        //            pictureBox3.Image = Image.FromFile(file);
        //        }
        //        catch
        //        { }
        //    }
        //    else
        //    {

        //    }
        //    GC.Collect();
        //    timerPhoto.Start();
        //}
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            readSeting = File.ReadAllLines(Application.StartupPath + "\\" + "型号" + "\\" + comboBox1.Text + ".txt", Encoding.UTF8);
            //contents = File.ReadAllLines(Application.StartupPath + "\\COM口配置.txt", Encoding.UTF8);
            PLC_Link[0].plc.Write(DataType.DataBlock, 99, 5, Convert.ToByte(comboBox1.SelectedIndex + 1));
            if (pictureBox3.Image != null)
            {
                pictureBox3.Image.Dispose();
            }
            pictureBox3.Image = null;       //切换型号时也清除显示的SOP便于显示新的型号
            if (comboBox1.SelectedIndex == 0)   ////切换产品时也切换标题
            {
                label3.Text = "辅线OP10-3";
            }
            else if (comboBox1.SelectedIndex == 1)
            {
                label3.Text = " 辅线OP01";
            }
            else
            {

            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            OpenForm(new FormDataSelect());
        }
        //手动模式
        private void button5_Click(object sender, EventArgs e)
        {
            PLC_Link[0].WriteBoolen("DB1050.DBX0.0", false);
            PLC_Link[0].WriteBoolen("DB1050.DBX0.1", true);
            if ((Program.userlogin.UserID == 1) || (Program.userlogin.UserID == 2))      //登录账户有操作权限
            {
                OpenForm(new FormManMode());
            }
            else    //进行登录操作
            {
                MessageBox.Show("没有操作权限", "提示！");
                return;
            }
        }
        //自动模式
        private void button9_Click(object sender, EventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB1050.DBX0.1", false);
            FormMain.PLC_Link[0].WriteBoolen("DB1050.DBX0.0", true);
            CloseForm();
        }
        //计数清零
        private void button2_MouseDown(object sender, MouseEventArgs e)
        {
            PLC_Link[0].WriteBoolen("DB99.DBX10.3", true);
        }
        private void button2_MouseUp(object sender, MouseEventArgs e)
        {
            PLC_Link[0].WriteBoolen("DB99.DBX10.3", false);
        }
        //报警复位按钮
        private void button10_MouseDown(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB1050.DBX1.2", true);
        }
        private void button10_MouseUp(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB1050.DBX1.2", false);
        }
        //强制不合格按钮
        private void button12_MouseDown(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB1050.DBX1.5", true);
        }

        private void button12_MouseUp(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[0].WriteBoolen("DB1050.DBX1.5", false);
        }
        //查看拍照按钮
        private void button11_MouseDown(object sender, MouseEventArgs e)
        {
            if (!Photoshow)     //按下按钮时进行取反
            {
                Photoshow = true;
            }
            else
            {
                Photoshow = false;
            }
        }
        private void button11_MouseUp(object sender, MouseEventArgs e)
        {
            if (Photoshow)  //松开按钮时根据Photoshow进行判断是否显示照片
            {
                //timerPhoto.Enabled = true;
                //timerPhoto.Interval = 1000;
                //timerPhoto.AutoReset = false;
                //timerPhoto.Elapsed += new System.Timers.ElapsedEventHandler(timerPhoto_Elapsed);
                ////List<Label> lab = new List<Label> { useTable1, useTable2, useTable3, useTable4, useTable5, useTable6, useTable7, useTable8, useTable9, useTable10, useTable11, useTable12, useTable13, useTable14 };
                ////for (int i = 0; i < 14; i++)
                ////{
                ////    lab[i].Visible = false;
                ////}
                //timerPhoto.Start();
                string filePath = GetLatestPhoto();
                if (!string.IsNullOrEmpty(filePath))
                {
                    if (pictureBox3.Image != null)
                    {
                        pictureBox3.Image.Dispose();
                    }
                    // 显示最新照片
                    pictureBox3.BackgroundImage = Image.FromFile(filePath);

                }
            }
            else
            {
                //timerPhoto.Stop();
                if (pictureBox3.Image != null)
                {
                    pictureBox3.Image.Dispose();
                }
                pictureBox3.Image = null;
            }
        }
        //获取最新照片
        public string GetLatestPhoto()      
        {
            // 指定你的照片文件所在的目录
            string directoryPath = "D:\\Photo";

            // 获取指定目录下的所有照片文件
            string[] photoFiles /*= Directory.GetFiles(directoryPath, "*.jpg")*/;
            //if (photoFiles == null || photoFiles.Length == 0)
            //{
            photoFiles = Directory.GetFiles(directoryPath, "*.jpeg");
            //}
            //if (photoFiles == null || photoFiles.Length == 0)
            //{
            //    photoFiles = Directory.GetFiles(directoryPath, "*.png");
            //}
            //if (photoFiles == null || photoFiles.Length == 0)
            //{
            //    photoFiles = Directory.GetFiles(directoryPath, "*.bmp");
            //}
            // 按修改日期排序，最新的照片会在数组的最后面
            Array.Sort(photoFiles, (x, y) => new FileInfo(x).LastWriteTime.CompareTo(new FileInfo(y).LastWriteTime));

            // 返回最新的照片文件路径
            return photoFiles.Length > 0 ? photoFiles[photoFiles.Length - 1] : null;
        }
        //转存照片
        public void MoveAndRenameLatestPhoto(string newFolderPath, string newFileName)
        {
            string filePath = GetLatestPhoto();

            if (filePath.Contains("jpeg"))
            {
                newFileName += ".jpeg";
            }
            //else if (filePath.Contains("jpg"))
            //{
            //    newFileName += ".jpg";
            //}
            //else if (filePath.Contains("png"))
            //{
            //    newFileName += ".png";
            //}
            //else if (filePath.Contains("bmp"))
            //{
            //    newFileName += ".bmp";
            //}
            if (!string.IsNullOrEmpty(filePath))
            {
                // 构建新的文件路径
                string newFilePath = Path.Combine(newFolderPath, newFileName);
                if (!Directory.Exists(newFolderPath))
                {
                    Directory.CreateDirectory(newFolderPath);
                }
                // 移动并重命名照片文件
                try
                {
                    File.Move(filePath, newFilePath);
                }
                catch (Exception e)
                {
                    if (e.ToString().Contains("当文件已存在时，无法创建该文件"))
                    {
                        MessageBox.Show("照片记录中已有名为" + newFileName + "的照片，请检查当前零件码！", "错误提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    }
                    else
                    {
                       
                    }

                }

            }
        }
        
    }
}
